// Copyright DustedPixels.com 2008. All rights reserved.

package com.dustedpixels.asm.analysis;

import java.util.HashSet;
import java.util.Set;

import junit.framework.TestCase;

import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.analysis.Analyzer;
import org.objectweb.asm.tree.analysis.Frame;
import org.objectweb.asm.tree.analysis.Interpreter;

import com.dustedpixels.asm.tree.TreeUtils;


/**
 * @author micapolos@gmail.com (Michal Pociecha-Los)
 */
public final class TargetInterpreterTest extends TestCase {
  MethodNode method;
  Frame[] frames;
  
  public void testSimple() throws Exception {
    setupMethod("(LObject;)LObject;");
    method.visitVarInsn(Opcodes.ALOAD, 0);
    method.visitInsn(Opcodes.ARETURN);    
    analyze();
   
    assertEquals(
        getTargetValue(frames[1], 0).getTargets(),
        method.instructions.get(1));
  }
  
  private TargetValue getTargetValue(Frame frame, int stackIndex) {
    return (TargetValue) frame.getStack(stackIndex);
  }

  private void setupMethod(String desc) {
    method = new MethodNode(0, "foo", desc, null, new String[0]);
    method.visitCode();
  }
  
  private void analyze() throws Exception {
    method.visitMaxs(100, 100);
    method.visitEnd();
    Interpreter interpreter = new TargetInterpreter();
    Analyzer analyzer = Analyzers.newUsing(interpreter);
    frames = analyzer.analyze("Foo", method);
  }
  
  private void assertTargets(Set<AbstractInsnNode> resultTargets, 
      AbstractInsnNode... expectedTargets) {
    Set<AbstractInsnNode> expectedTargetsSet = new HashSet<AbstractInsnNode>();
    for (AbstractInsnNode expectedTarget : expectedTargets) {
      expectedTargetsSet.add(expectedTarget);  
    }
    assertEquals(expectedTargetsSet, resultTargets);
  }
}
